<?php

namespace app\admin\model;

use app\admin\validate\Notes as ValidateNotes;
use think\Model;

class Notes extends Model
{
    public function Getnoteslist($data)
    {
        $result = db('notes')
            ->alias('n')
            ->join("app a", "a.appid=n.appid")
            ->join("user u", "u.id=n.user_id")
            ->field("n.*,a.appname,u.username")
            ->where("n.title", "like", "%{$data['title']}%")
            ->order($data['sort'], $data['sortOrder'])
            ->limit($data['limit'])
            ->page($data['page'])
            ->select();
        $count = db('notes')
            ->alias('n')
            ->join("app a", "a.appid=n.appid")
            ->field("n.*,a.appname")
            ->where("n.title", "like", "%{$data['title']}%")
            ->order($data['sort'], $data['sortOrder'])
            ->limit($data['limit'])
            ->page($data['page'])
            ->count();
        return json(["rows" => $result, "total" => $count]);
    }

    public function deletenotes($id)
    {
        if (!is_array($id)) {
            return "服务器错误";
        }
        foreach ($id as $key => $value) {
            $this->where("id", $value)->delete();
        }
        return 1;
    }

    public function getappinfo($id)
    {
        $result = db('notes')
            ->alias('n')
            ->join("app a", "a.appid=n.appid")
            ->join("user u", "u.id=n.user_id")
            ->field("n.*,a.appname,u.username")
            ->where("n.id", "{$id}")
            ->find();
        return $result;
    }

    public function edit($data)
    {
        $validate = new ValidateNotes();
        if (!$validate->scene('edit')->check($data)) {
            return $validate->getError();
        }
        $id = $data["id"];
        unset($data["id"]);
        $data["updatetime"] = date("Y-m-d H:i:s",time());
        $data["ip"] = get_real_ip();
        $this->allowField(true)->save($data,["id"=>$id]);
        return 1;
    }

}
